﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Interfaces;
using Domain;

namespace Server
{
    internal class EmployeeService : IEmployeeService
    {
        public List<Employee> GetEmployees(string lastNameBeginsWith)
        {
            using (InheritanceTypeContext context = new InheritanceTypeContext())
            {

                List<Employee> employees = (from e in context.Person.OfType<Employee>().Include("TeamLeader").Include("TeamMembers")
                        where e.Lastname.StartsWith(lastNameBeginsWith)
                        select e).ToList();

                
                employees.ForEach(p => context.PrepareForSerialization(p)) ;
                return employees;
            }
        }


        public Person SavePerson(Person person)
        {
            using (InheritanceTypeContext context = new InheritanceTypeContext())
            {
                context.AttachToContext(person);

                context.SaveChanges();

                context.PrepareForSerialization(person);

                return person;
            }
        }


        public Employee GetEmployee(int id)
        {
            using (InheritanceTypeContext context = new InheritanceTypeContext())
            {
                Employee employee = (from e in context.Person.OfType<Employee>().Include("TeamLeader").Include("TeamMembers")
                                     where e.PersonID == id
                                     select e).FirstOrDefault();

                if (employee != null)
                    context.PrepareForSerialization(employee);
                
                return employee;
            }
        }
    }
}
